package com.toe.forum.webapi.controller;

import com.toe.forum.webapi.utils.UploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@Slf4j
@Api(tags = "上传文件模块")
public class UploadController {
    private static  String IMG = "image";
    private static  String VIDEO = "video";

    @Value("${dirPath}")
    private static String dirPath;

    @ApiOperation("上传文件")
    @PostMapping("/upload/one")
    public String upload(MultipartFile picFile, HttpServletRequest request) throws IOException{
        //如果文件数组为0，则表示没有上传文件
        if (picFile == null){
            log.info("无上传文件");
            return "无上传文件";
        }
        //调用utils获取文件名
        String fileName = UploadUtils.upload(picFile);
        return fileName;
    }

    @ApiOperation("上传很多文件")
    @PostMapping("/upload/file")
    public List<String> uploads(MultipartFile[] file , HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
        //获得已经上传到硬盘的文件名
        Map<String, List<String>> files = UploadUtils.upload(file);
        List<String> img = files.get(IMG);
        List<String> video = files.get(VIDEO);
        img.addAll(video);
        return img;
    }

    @ApiOperation("删除文件")
    @GetMapping("/remove")
    public void remove(String name){
        String filePath = dirPath+"/"+name;
        new File(filePath).delete();//删除文件
    }
}
